package org.springframework.samples.travel.infrastructure.security;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.samples.travel.application.Factory;
import org.springframework.samples.travel.domain.model.user.UserRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class MongoUserDetailsService implements UserDetailsService {

    public static int connectionsTotalAmount = 0;

    public static int connectionsFailedAmount = 0;

    private final UserRepository userRepo;

    @Inject
    public MongoUserDetailsService(UserRepository userRepository) {
	this.userRepo = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	Factory.getCountingService().incrementTotalConnections();
	org.springframework.samples.travel.domain.model.user.User tmp = userRepo.findByUsername(username);
	if (tmp == null)
	    throw new UsernameNotFoundException("invalid user name");
	List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
	if (tmp.getRoles() == null || tmp.getRoles().isEmpty())
	    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
	else {
	    for (String role : tmp.getRoles())
		authorities.add(new SimpleGrantedAuthority(role));
	}
	Factory.getCountingService().incrementTotalSuccessfulConnections();
	return new User(tmp.getUsername(), tmp.getPassword(), authorities);
    }
}
